package com.traitswu.websocket.utils;

import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;

import javax.script.*;
import java.util.Map;

/**
 * Created by xiaoquan on 17-5-26.
 */
public class GroovyScriptService {

    public Object execute(String script, Map<String, Object> properties) {
        try {
            CompiledScript compiledScript = compile(script);

            SimpleBindings bindings = new SimpleBindings();
            bindings.putAll(properties);
            return compiledScript.eval(bindings);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }

    protected CompiledScript compile(String script) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("groovy");


            GroovyScriptEngineImpl engine1 = (GroovyScriptEngineImpl) engine;


            return ((Compilable) engine).compile(script);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }


}
